from api.fcoin3 import Fcoin
#时区设置模块
import pytz
import datetime
import time
from setting import *
import json
import math

class Tool():
    def __init__(self, fcoin):
        self.fcoin = fcoin


    def check_hour_ave(self, resolution, symbol):
        tz = pytz.timezone('Asia/Shanghai')
        now = datetime.datetime.now(tz)
        # now.minute,获取now下的分钟，CANDLE-RATE下的列表，时间间隔
        limit_len = int(now.minute/CANDLE_RATE[resolution])
        data = self.fcoin.get_candle(resolution, symbol, limit = limit_len)['data']

        base_vol = 0
        quote_vol = 0
        for candle in data:
            base_vol += candle['base_vol']
            quote_vol += candle['quote_vol']
        print('%s base_vol is %f, quote_vol is %f' %(symbol, base_vol, quote_vol))
        return quote_vol/base_vol

    def currency_by_symbol(self, symbol):
        symbols = self.fcoin.get_symbols()
        for symbol_item in symbols:
            if symbol_item['name'] == symbol:
                base_currency = symbol_item['base_currency']
                quote_currency = symbol_item['quote_currency']
        return base_currency, quote_currency

    def get_trade_balance(self, symbol):
        base_currency, quote_currency = self.currency_by_symbol(symbol)
        ticker_data = self.fcoin.get_market_ticker(symbol)['data']['ticker']
        price = ticker_data[0]
        balances = self.fcoin.get_balance()['data']

        for i in range(0, len(balances)):
            if balances[i]['currency'] == base_currency:
                base_balance = float(balances[i]['balance'])
                base_balance_v = float(balances[i]['available'])

            if balances[i]['currency'] == quote_currency:
                quote_balance = float(balances[i]['balance'])/price
                quote_balance_v = float(balances[i]['balance'])/price

        return base_balance+quote_balance, base_balance_v+quote_balance_v

    def get_min_trade_amount(self, symbol):
        base_currency, quote_currency = self.currency_by_symbol(symbol)

        balance_list = self.fcoin.get_balance()['data']
        for balance in balance_list:
            if balance['currency'] == base_currency:
                base_currency_amount = float(balance['available'])
            if balance['currency'] == quote_currency:
                quote_currency_amount = float(balance['available'])

        return base_currency_amount, quote_currency_amount


    def calculate_trade_amount_price(self, symbol):
        ticker_data = self,fcoin.get_market_ticker(symbol)['data']['ticker']
        max_buy_one_price = ticker_data[2]
        max_buy_one_amount = ticker_data[3]
        min_sell_one_price = ticker_data[4]
        min_sell_one_amount = ticker_data[5]

        base_currency_amount, quote_currency_amount = self.get_min_trade_amount(symbol)

        if min_sell_one_price - max_buy_one_price >0:
            buy_price = sell_price = float('%0.8f' %(min_sell_one_price-0.00000001))
            cal_min_trade_amount = min(int(base_currency_amount), int(quote_currency_amount/sell_price), MIN_TRADE_AMOUNT)
        else:
            buy_price = min_sell_one_price
            sell_price = max_buy_one_price
            cal_min_trade_amount = min(max_buy_one_amount, min_sell_one_amount, int(base_currency_amount), int(quote_currency_amount/sell_price), MIN_TRADE_AMOUNT)

        return buy_price, sell_price, cal_min_trade_amount



    def get_currency_balance(self, currency):
        balances = self.fcoin.get_balance()['data']
        for balance in balances:
            if balance['currency'] == currency:
                return balance['balance']

    #80秒后订单取消
    def cancel_order_by_time(self, symbol, timecancel=80):
        # list_orders
        sub_orders = self.fcoin.list_orders(states='submitted', symbol=symbol)
        if sub_orders:
            # 遍历
            for order in sub_orders['data']:
                nowtime = time.time()
                create_time = order['created_at']/1000
                if(nowtime-create_time >timecancel):
                    print('cancel order id is %s, create_at %s' %(order['id'], order['created_at']))
                    self.fcoin.cancel_order(order['id'])
                    time.sleep(2)

        time.sleep(2)

        pf_orders = self.fcoin.list_orders(states='partial_filled', symbol=symbol)
        if pf_orders:
            # 根据时间限制，取消订单
            for order in pf_orders['data']:
                nowtime = time.time()
                create_time = order['created_at']/1000
                if(nowtime-create_time >timecancel):
                    print('cancel order id is %s, create_at %s' %(order['id'], order['created_at']))
                    self.fcoin.cancel_order(order['id'])
                    time.sleep(2)





if __name__ == '__main__':

    fcoin = Fcoin()
    fcoin.auth(FCOIN_KEY, FCOIN_SECRET)
    tool = Tool(fcoin)
    # print(tool.check_hour_ave('M1', 'fteth'))
    # print(tool.get_trade_balance('ethusdt'))
    # print(tool.get_min_trade_amount('ethusdt'))
    ft = tool.get_currency_balance('ft')
    print(ft, type(ft))
    #print(tool.cancel_order_by_time('ethusdt'))
    

